package com.atguigu.educenter.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.educenter.client.EduTimeStampClient;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.entity.vo.timestampVo;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.handler.GuiliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Optional;

//@CrossOrigin
@Controller  //只是请求地址，不需要返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @Autowired
    private EduTimeStampClient eduTimeStampClient;

    //2 获取扫描人信息，添加数据
    @GetMapping("callback")
    public String callback(@RequestParam("app_id") String APP_ID, @RequestParam("auth_code") String code) throws AlipayApiException {
        String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnvqA1X9+xyhXkxd/s8YzY7YIPmb/IMA0eFMPipCu6npTC+VLH1ufXqrln4ZsiU8GtumXZkar4FoDy/1wDAFXrH7WK+0/PwQvD0JV8fu0kHVPJJToSO9zt4OYcBUvPEfvW8xYFa6lQ6tzxkMbxgbdJBb2RtRhsICE9m4BMlqarJ7YpVN1Bpwt/uk83q/7MMLll5bdicCo3izpWQED4Xy3VNo7InioE7vd7h41AzVPyck9zxfwYAXzO3nRHu26pPAo15jyUEgv+Lq+NAxuRT32fvT2WJGcmNIBoopbixqiP4+AJEuKn8t1eggsS0Ht8enCDWxyulbsaOaJDc7bVwUN9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RNNJ7WdnHT1Uh0/CJFbA9mf1Q9vhwKBgQCzp3gttSkQqhN0gZO+XTT1wV3shxQPDzKW7V3ijUPqYp73l+SHt5oRDDJCz2yS0LMewbI/24ufPuIpEtpV6+NcuTgoGDaGVbUeIzvh3YbC+vvf98VL1k1B38HvHP3EyAr9FRUeXviK55LmHFy6bpzwdG3goJZg5DLsaT6A1hktOQKBgBrJtuNs5byCcSn/T+8zP1Q8uJ04tCz4V7TBXHK+F3jPVEXx7s9OFOR1saM4MnRkedYWywtKZGOhKL9vQ0uidyukY0pY3PyOddapl8+D+bK2a7PEYe6dMtdJwhojTTGRgFqaxnX7hh37/uDyIEFY7D0jYzqQjUgpmD4yVcBxaxqTAoGBAJUtum9Qk+l4zz+3k9R+ibQHVtlRkNoj/GAIVNtUTUA/z/3iWoDj8u5lFSEdrLl2/cinO7tS6KI+KswMX2NxmYC8t1UCGcu/w2Nbn11cWIgAEC6nDvdhSSezwaS9MsrmcUj4p09HkUyZyWamPmV7DgJ0xDirgYCnDDid5ERKwXYw";
        String CHARSET = "utf-8";
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        AlipayUserInfoShareRequest userrequest = new AlipayUserInfoShareRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            String accessToken = oauthTokenResponse.getAccessToken();
            AlipayUserInfoShareResponse userinfo = alipayClient.execute(userrequest, accessToken);
            String nickName = userinfo.getNickName();
            String photo = userinfo.getAvatar();
            String openid = userinfo.getUserId();
            String phone = userinfo.getPhone();
            Optional<UcenterMember> optional = Optional.ofNullable(memberService.getOpenIdMember(openid));
            UcenterMember ucenterMember = new UcenterMember();
            if (!optional.isPresent()){
                ucenterMember.setNickname(nickName);
                ucenterMember.setOpenid(openid);
                ucenterMember.setAvatar(photo);
                ucenterMember.setMobile(phone);
                memberService.save(ucenterMember);

                timestampVo timestampVo = new timestampVo();
                timestampVo.setContent("这是您第一次走进信工开源的世界！");
                timestampVo.setTitle("第一次注册");
                timestampVo.setTime(new Date());
                eduTimeStampClient.saveTs(timestampVo);

            }
            String jwtToken = JwtUtils.getJwtToken(memberService.getOpenIdMember(openid).getId(), memberService.getOpenIdMember(openid).getNickname());
            //最后：返回首页面，通过路径传递token字符串
            return "redirect:http://localhost:3000?token="+jwtToken;

        } catch (AlipayApiException e) {
            //处理异常
            throw new GuiliException(20001,"登录失败");
        }
    }

    //1 生成支付宝扫描二维码
    @GetMapping("login")
    @ResponseBody
    public R getWxCode() {
        String appid = "2021000117605715";
        String redirect_uri = "http://127.0.0.1:8150/api/ucenter/wx/callback";//扫描成功后回调地址
        try {
            redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?app_id=" + appid + "&scope=auth_user&redirect_uri=" + redirect_uri;
        return R.ok().data("urls",url);
    }
}
